/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gr.search;

import java.io.File;
import java.io.IOException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermPositions;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import com.gr.zoie.DocIDMapper;
import com.gr.zoie.DocIDMapperImpl;

/**
 *
 * @author ADMIN
 */
public class Mapper {
    public DocIDMapper getDocIDMapper(String indexDir) throws IOException
   {
       long _minUID = Long.MAX_VALUE;
       long _maxUID = 0;
       Directory dir = FSDirectory.open(new File(indexDir));
       IndexReader reader = IndexReader.open(dir);
       int maxDoc = reader.maxDoc();
       long[] _uidArray = new long[maxDoc]; 
       TermPositions tp = null;
       byte[] payloadBuffer = new byte[8];       // four bytes for a long
       try
       {
          tp = reader.termPositions(new Term("docID","_UID"));
          int idx = 0;
          while (tp.next())
          {
            int doc = tp.doc();
            assert doc < maxDoc;
            
            while(idx < doc) _uidArray[idx++] = Long.MIN_VALUE; // fill the gap
            
            tp.nextPosition();
            tp.getPayload(payloadBuffer, 0);
            long uid = bytesToLong(payloadBuffer);
            if(uid < _minUID) _minUID = uid;
            if(uid > _maxUID) _maxUID = uid;
            _uidArray[idx++] = uid;
          }
          while(idx < maxDoc) _uidArray[idx++] = Long.MIN_VALUE; // fill the gap
      }
      finally
      {
          if (tp!=null)
          {
                  tp.close();
          }
      }
      return new DocIDMapperImpl(_uidArray);
   }
   private long bytesToLong(byte[] bytes){
        return ((long)(bytes[7] & 0xFF) << 56) | ((long)(bytes[6] & 0xFF) << 48) | ((long)(bytes[5] & 0xFF) << 40) | ((long)(bytes[4] & 0xFF) << 32) | ((long)(bytes[3] & 0xFF) << 24) | ((long)(bytes[2] & 0xFF) << 16)
           | ((long)(bytes[1] & 0xFF) <<  8) |  (long)(bytes[0] & 0xFF);
   }
}
